package lazy2.util;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class FileSearcher {
	private FileTree fileTree = new FileTree();
	private KeywordChecker keywordChecker = new KeywordChecker();
	public List<File> searchInFile(String[] keywords, File file) throws FileNotFoundException {
		fileTree.changeFileRoot(file);
		List<File> tree = fileTree.getFiles();
		List<File> resultFiles = new ArrayList<File>(tree.size());
		for(String keyword:keywords) {
			keywordChecker.addKeyword(keyword);
		}
		BufferedInputStream bi = null;
		byte[] b = new byte[1024];
		int i,len;
		for(File f:tree) {
			try {
				bi = new BufferedInputStream(new FileInputStream(f));
				READ_DATA:
				while((len=bi.read(b))!=-1) {
					for(i=0;i<len;i++) {
						if(keywordChecker.isChecked(b[i])) {
							resultFiles.add(f);
							break READ_DATA;
						}
					}
				}
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				keywordChecker.reset();
				if (bi!=null) {
					try {
						bi.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}
		return resultFiles;
	}
}
